import { Button, Checkbox, Form, Input } from 'antd';
import React from 'react';
import * as api from "@/api/use"
import useStorage from '@/hooks/useStorage';
import { useNavigate } from "react-router-dom"

//校验函数

//用户名校验
let nameFn = (rules:any,value:string) => {
    if(!value) {
        return Promise.reject('用户名不能为空')
    }
    if(value.length<3) {
        return Promise.reject('用户名长度不可小于三位')
    }else{
      return Promise.resolve()
  }
}
//密码校验
let usernameFn = (rules:any,value:string) => {
    if(!value) {
        return Promise.reject('用户名不能为空')
    }
    if(value.length<3) {
        return Promise.reject('用户名长度不可小于三位')
    }else{
        return Promise.resolve()
    }
}

//登入请求传递参数的类型
declare global {
  interface loginParam {
    username:string;
    password:string;
    remeber:boolean
  }
}

const Login: React.FC = () => {
  //使用自定义的本地存储
  let [, tokenMethod] = useStorage('qf-token')
  let [, useMethod] = useStorage('user-info')
  let [, permissionMethod] = useStorage('btn-permission')
  //跳转hook
  let navigate = useNavigate()
  //表单校验通过
  const onFinish = (values: loginParam) => {
    // console.log('Success:', values);
    //发起登录
    api.LoginApi(values)
    .then((res:any) => {
      // console.log(res);
      //登入成功
      if(res.data.state) {
        // 1 存token
        tokenMethod.set(res.data.token)
        //2 存用户信息
        useMethod.set(res.data.userInfo)
        //3 存按钮权限
        permissionMethod.set(res.data.permission)
        //4 跳转到主页
        navigate("/")
      }

      
    })
  };
  //表单校验失败
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Form
      name="loginFrom"
      labelCol={{ span: 2 }}
      wrapperCol={{ span: 5 }}
      initialValues={{ remember: true }}
      onFinish={onFinish}    //表单校验通过
      onFinishFailed={onFinishFailed}   //表单校验失败
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, validator:nameFn }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, validator:usernameFn }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 2, span: 5 }}>
        <Checkbox>7天免登录</Checkbox>
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 2, span: 5 }}>
        <Button type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Login